var supplierObj = [];
var limit = 15;
var tid;
var orgObj = convertOrgToObj(orgList);
layui.use(['laypage','laydate', 'table', 'form'], function(){
    var table = layui.table;
    var form = layui.form;

    let todoCols = [
        [
            {field: 'id', title: '标识', width:80, align: 'center', hide: true}
            ,{field: 'orgId', title: '公司名称', width:105, align: 'center',templet:function (val) {
                return orgObj[val.orgId];
            }}
            ,{field: 'code', title: '编码', width: 120, align: 'center',templet: function (val) {
                if (isNull(val.code)) {
                    return "";
                }
                return '<div style="white-space: pre-wrap;">' + val.code + '</div>';
            }}
            ,{field: 'name', title: '名称', width: 140, align: 'center',templet: function (val) {
                if (isNull(val.name)) {
                    return "";
                }
                return '<div style="white-space: pre-wrap;">' + val.name + '</div>';
            }}
            ,{field: 'producer', title: '产家', width: 150, align: 'center',templet: function (val) {
                if (isNull(val.producer)) {
                    return "";
                }
                return '<div style="white-space: pre-wrap;">' + val.producer + '</div>';
            }}
            ,{field: 'ip', title: 'IP地址', width: 100, align: 'center',templet: function (val) {
                if (isNull(val.ip)) {
                    return "";
                }
                return '<div style="white-space: pre-wrap;">' + val.ip + '</div>';
            }}
            ,{field: 'driver', title: '连接驱动', width: 100, align: 'center',templet: function (val) {
                if (isNull(val.driver)) {
                    return "";
                }
                return '<div style="white-space: pre-wrap;">' + val.driver + '</div>';
            }}
            ,{field: 'url', title: '连接地址', width:100, align: 'center'}
            ,{field: 'username', title: '用户名', width: 100, align: 'center'}
            ,{field: 'password', title: '密码', width: 180, align: 'center'}
            ,{field: 'type', title: '数据库类型', width:130, align: 'center', templet:function (val) {
                if (val.type == 0)
                    return 'mysql';
                else  if (val.type == 1)
                    return 'sqlserver';
                else
                    return 'oracle';
            }}
            ,{field: 'status', title: '状态', width:130,align: 'center', templet:function (val) {
                if (val.status == 0)
                    return '启用';
                else
                    return '禁用';
            }}
            ,{field: 'remark', title: '备注', width: 220, align: 'center'}
            ,{field: 'creator', title: '创建人', width: 120, align: 'center'}
            ,{field: 'createTime', title: '创建时间', width: 180, align: 'center'}
            ,{fixed: 'right', title:'操作', width: 260, align:'center', templet:function (val) {
                var str = '<a lay-event="detail" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-primary">详情</a>';
                if (val.status == 0){
                    if (isDelete == 1)
                    str += '<a lay-event="delete" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-danger">禁用</a>';
                    if (isUpdate == 1)
                    str += '<a lay-event="edit" href="javascript:void(0)" class="layui-btn layui-btn-xs">编辑</a>';
                }else{
                    if (isDelete == 1)
                    str += '<a lay-event="delete" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-danger">启用</a>';
                }
                return str;
            }}
        ]
    ];

    table.render({
        elem: '#body-list'
        ,url: '/system/sysLine/page'
        ,method: 'post'
        ,page: true
        ,contentType: 'application/json'
        ,cols: todoCols
        ,limit: limit
        ,limits: [15,30,50,100]
        ,request: {
            pageName: 'curr' //页码的参数名称，默认：page
            ,limitName: 'limit' //每页数据量的参数名，默认：limit
        }
        ,where: {
            offset: 0,
            limit: limit,
            orgId:$('.search-origin').val(),
        }
        ,parseData: function(res){ //res 即为原始返回的数据
            console.log(res);
            if (res.code == 0 && res.data != null) {
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.records //解析数据列表
                };
            } else {
                return {
                    "code": res.code, //解析接口状态
                    "msg": '没有任何数据', //解析提示文本
                    "count": 0, //解析数据长度
                    "data": '' //解析数据列表
                };
            }
        }
    });

    //监听行工具事件
    table.on('tool(body-list)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
        var data = obj.data //获得当前行数据
            ,layEvent = obj.event; //获得 lay-event 对应的值
        if(layEvent === 'delete'){

            var id = data.id;
            var status = data.status;
            var tip = '是否要启用？';
            if (status == 0)
                tip = '是否要禁用？';
            layer.confirm(tip, {
                btn: ['确定', '取消']
            }, function(index, layero){
                var updateStatus = 0;
                if (status == 0)
                    updateStatus = 1;
                var option =  '{"id": '+id+', "status":'+updateStatus+'}';
                save(option, "/system/sysLine/updatestatus");
            }, function(index){
            });
        } else if(layEvent === 'edit'){
            tid = data.id;
            $("#updateTitle").text("修改新增生产线");
            $('.updateModal').show();
            $(".update-search-origin").val(data.orgId);
            $(".update-producer").val(data.producer);
            $(".update-code").val(data.code);
            $(".update-name").val(data.name);
            $(".update-url").val(data.url);
            $(".update-driver").val(data.driver);
            $(".update-username").val(data.username);
            $(".update-password").val(data.password);
            $(".update-type").val(data.type);
            $(".update-ip").val(data.ip);
            $(".update-remark").val(data.remark);
            $("#updateBtn").show();
            form.render();
        } else  if(layEvent === 'detail'){
            $("#updateTitle").text("查看生产线");
            $('.updateModal').show();
            $(".update-search-origin").val(data.orgId);
            $(".update-producer").val(data.producer);
            $(".update-code").val(data.code);
            $(".update-name").val(data.name);
            $(".update-url").val(data.url);
            $(".update-driver").val(data.driver);
            $(".update-username").val(data.username);
            $(".update-password").val(data.password);
            $(".update-type").val(data.type);
            $(".update-ip").val(data.ip);
            $(".update-remark").val(data.remark);
            $("#updateBtn").hide();
            form.render();
        }
    });

    form.on('select(search-status)', function(data) {
        $(".btn-query").trigger("click");
    });
    form.on('select(search-url)', function(data) {
        $(".btn-query").trigger("click");
    });
    form.on('select(search-type)', function(data) {
        $(".btn-query").trigger("click");
    });
    form.on('select(search-origin)', function(data) {
        $(".btn-query").trigger("click");
    });

    $('.btn-query').on('click', function () {//搜索按钮
        var searchVal = $('.search-text').val();
        var status = $('.search-status').val();
        var orgId = $('.search-origin').val();
        var type = $('.search-type').val();
        var url = $('.search-url').val();

        var option = {page:1,limit:limit};
        if (!isNull(searchVal))
            option['searchVal'] = searchVal;
        if (!isNull(orgId))
            option['orgId'] = orgId;
        if (!isNull(status))
            option['status'] = status;
        if (!isNull(type))
            option['type'] = type;
        if (!isNull(url))
            option['url'] = url;
        table.reload('body-list', {
            where: option
        });
    });

    $("#update-mainDiscount-body .close").on("click", function() {
        $("#update-mainDiscount-body").hide();
        $("#update-mainDiscount-body-body input").val("");
        $("#update-mainDiscount-body select").val("");
        $("#update-mainDiscount-body textarea").val("");
        $(".qrcode-show").hide();
        form.render();
        tid = -1;
    });

    form.on('submit(updateBtns)', function() {
        var option = null;
        var orgId = $(".update-search-origin").val();
        var producer = $(".update-producer").val();
        var code = $(".update-code").val();
        var name = $(".update-name").val();
        var ip = $(".update-ip").val();
        var driver = $(".update-driver").val();
        var username = $(".update-username").val();
        var password = $(".update-password").val();
        var url = $(".update-url").val();
        var type = $(".update-type").val();
        var remark = $(".update-remark").val();
        option = '{"id":'+tid+', "orgId":'+orgId+', "producer":"'+producer+'", "code":"'+code+'", "name":"'+name+'", "ip":"'+ip+'", "driver":"'+driver+'", "username":"'+username+'", "password":"'+password+'", "url":"'+url+'", "type":"'+type+'", "remark":"'+remark+'" }';
        if (isNull(tid) || tid == -1) {
            layer.msg("获取修改信息错误,请刷新再试！");
            return ;
        }
        save(option, "/system/sysLine/update");
    });


    //打开新增页面
    $('.btn-add').on('click', function () {//新增流程
        if (isInsert == 0) {
            layer.msg('您没有添加权限~!');
            return ;
        }
        $('.addModal').show();
    });

    //关闭新增页面
    $(".addModal .close").on("click", function () {//关闭新增流程窗口
        $(".addModal").hide();
        $(".addModal input").val("");
        $(".addModal select").val("");
        $(".addModal textarea").val("");
        form.render();
    });

    //新增
    form.on('submit(addBtns)', function () {
        var option = null;
        var orgId = $(".add-search-origin").val();
        var producer = $(".add-producer").val();
        var code = $(".add-code").val();
        var name = $(".add-name").val();
        var ip = $(".add-ip").val();
        var driver = $(".add-driver").val();
        var username = $(".add-username").val();
        var password = $(".add-password").val();
        var url = $(".add-url").val();
        var type = $(".add-type").val();
        var remark = $(".add-remark").val();
        option = '{"orgId":'+orgId+', "producer":"'+producer+'", "code":"'+code+'", "name":"'+name+'", "ip":"'+ip+'", "driver":"'+driver+'", "username":"'+username+'", "password":"'+password+'", "url":"'+url+'", "type":'+type+', "remark":"'+remark+'"}';
        save(option,"/system/sysLine/save");
    });


    function save(option, url) {//新增或修改
        var loading = layer.load(1);
        console.log(option);
        $.ajax({
            url: url,
            type: 'POST',
            dataType: 'json',
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            contentType: 'application/json',
            data: option,
            timeout: 30000,
            success: function(res) {
                layer.close(loading);
                if(res.code == 0) {
                    layer.msg("保存成功!");
                    table.reload('body-list', { where: {offset:0,curr:1,
                            limit: limit,
                            orgId:$('.search-origin').val() }});
                    $(".updateModal").hide();
                    $(".updateModal input").val("");
                    $(".updateModal select").val("");
                    $(".updateModal textarea").val("");
                    $(".addModal").hide();
                    $(".addModal input").val("");
                    $(".addModal select").val("");
                    $(".addModal textarea").val("");
                    form.render();
                } else {
                    layer.msg(res.msg);
                    return;
                }
            },
            error: function(res) {
                layer.msg("请求失败，请稍后再试！");
                layer.close(loading);
                return;
            },
            complete: function(XMLHttpRequest, status) {
                if(status == 'timeout') {
                    layer.msg("请求超时，请稍后再试！");
                    layer.close(loading);
                    return;
                }
            }
        })
    }


    $(document).keyup(function (event) {
        if (event.keyCode == 13) {
            $(".btn-query").trigger("click");
        }
    });
});